#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Contact info views
"""

from datetime import datetime

from django.shortcuts import render_to_response
from google.appengine.ext import db

from contact.common import json
from contact.models.softinfo import SoftInfo, SoftDownUrl
from contact.web.response import success_response, json_response

def _convert_datetime(s):
    return datetime.strptime(s, '%Y-%m-%d %H:%M:%S')

def save_softinfo(request):
    req = request.REQUEST
    last_modified = _convert_datetime(req['last_modified'])
    data = {'info': req['info'],
            'name': req['name'],
            'url': req['url'],
            'parent_url': req['parent_url'],
            'status': int(req['status']),
            'last_modified': last_modified,
            }
    if None:
        return success_response()
    query = SoftInfo.all()
    si = query.filter('url =', req['url']).get()
    if si is None:
        si = SoftInfo()
    si.save(data)
    return success_response()

def save_downurl(request):
    downurls = json.loads(request.REQUEST['downurls'])
    if isinstance(downurls, dict):
        downurls = [downurls]
    for info in downurls:
        info['last_modified'] = _convert_datetime(info['last_modified'])
        query = SoftDownUrl.all()
        di = query.filter('downurl =', info['downurl']).get()
        if di is None:
            di = SoftDownUrl()
        di.save(info)
    return success_response()

def get_softinfos(request):
    offset = int(request.GET.get('offset', 0))
    if offset < 0:
        offset = 0
    limit = int(request.GET.get('limit', 10))
    if limit > 50:
        limit = 10
    infos = SoftInfo.gql("ORDER BY last_modified DESC").fetch(limit, offset)
    total = SoftInfo.gql("ORDER BY __key__ DESC").get().key().id()
    data = {'softinfos': infos,
            'next': offset + limit,
            'limit': limit,
            'total': total}
    if offset > 0:
        prev = offset - limit
        if prev < 0:
            prev = 0
        data['prev'] = prev
        data['has_prev'] = True
    return render_to_response('soft/infolist.html', data)

def get_downloads(request, key):
    info = SoftInfo.get(db.Key(key))
    return json_response({'success': True, 
                          'downloads': info.download_infos()})
    
def clean_softinfos(request):
    infos = SoftInfo.gql("WHERE name=''").fetch(limit=1000)
    db.delete(infos)
    return success_response()